//
//  WPasswordPViewController.swift
//  iiatn
//
//  Created by mnine on 18/4/5.
//  Copyright © 2018年 mnine. All rights reserved.
//

import UIKit
import SVProgressHUD
import Alamofire
import SwiftyJSON
import SwiftKeychainWrapper


class WPasswordPViewController: itBaseViewController {

    
    @IBOutlet weak var pwdlabel: UILabel!
    
    @IBOutlet weak var newpwd: UITextField!
    
    @IBOutlet weak var confirmpwd: UITextField!
    
    @IBOutlet weak var tologin: UIButton!
    
    var mphone: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置导航栏的左右按钮
        setupBarButtonItem()
        setstyle()
        setdosth()
    }

    func setdosth(){
        tologin.addTarget(self, action: #selector(toLogin), for: .touchUpInside)
    }
    
    override func setupNav() {
        view.backgroundColor = UIColor.white
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    // MARK: - 设置导航栏按钮
    private func setupBarButtonItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action:
            #selector(cancelButtonClick))
    }

    func cancelButtonClick() {
        dismiss(animated: true, completion: nil)
    }
    
    func toLogin(){
        if(newpwd.text!.characters.count < 6){
            SVProgressHUD.showError(withStatus: "密码太短，不能低于6位！")
        }else if(newpwd.text! != confirmpwd.text!){
            SVProgressHUD.showError(withStatus: "两次密码不一致！")
        }else if(mphone!.isEmpty){
            print("phone is empty !")
            SVProgressHUD.showError(withStatus: "There is something throng！")
        }else{
            // ios/email/register  username password name
            let index = mphone?.index((mphone?.startIndex)!, offsetBy: 7)
            let url = BASE_URL + "apin/ios/phone/register"
            let params = ["username": mphone!,
                          "password": newpwd.text!,
                          "name": (mphone?.substring(from: index!))!] as [String : Any]
            print(url,mphone as Any,mphone?.substring(from: index!) as Any)
            Alamofire
                .request(url, method: .post, parameters: params)
                .responseJSON { (response) in
                    guard response.result.isSuccess else {
                        SVProgressHUD.showError(withStatus: "注册失败...")
                        return
                    }
                    if let value = response.result.value {
                        let dict = JSON(value)
                        let status = dict["status"].intValue
                        let msg = dict["msg"].stringValue
                        print(msg,status)
                        SVProgressHUD.showSuccess(withStatus: msg)
                        if status == 1 {
                            let data = JSON(dict["data"].dictionary!)
                            wuserid = data["id"].intValue
                            wphone = data["phone"].stringValue
                            wname = data["name"].stringValue
                            wemail = data["email"].stringValue
                            wprovince = data["province"].stringValue
                            wcity = data["city"].stringValue
                            print(whaslogin!)
                            NotificationCenter.default.post(name:NSNotification.Name(rawValue:"notifyNameMsgRecv"), object: nil, userInfo: nil)
                            whaslogin = true
                            self.rememberlogin()
                            self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
                        }
                    }
            }
            
        }
    }
    
    // MARK: - 设置风格
    func setstyle(){
        // 风格设置
        newpwd.isSecureTextEntry = true
        confirmpwd.isSecureTextEntry = true
        
        newpwd.width = SCREENW - pwdlabel.x*2 - pwdlabel.width-24
        confirmpwd.width = newpwd.width
        tologin.width = SCREENW - pwdlabel.x*2
        newpwd.x = SCREENW - newpwd.width - pwdlabel.x
        confirmpwd.x = newpwd.x
        
        
        tologin.layer.cornerRadius = tologin.height * 0.2
        tologin.layer.masksToBounds = true
        tologin.layer.rasterizationScale = UIScreen.main.scale
        newpwd.layer.cornerRadius = newpwd.height * 0.2
        newpwd.layer.masksToBounds = true
        newpwd.layer.borderWidth = 0.8
        newpwd.layer.borderColor = UIColor.gray.cgColor
        confirmpwd.layer.cornerRadius = confirmpwd.height * 0.2
        confirmpwd.layer.masksToBounds = true
        confirmpwd.layer.borderWidth = 0.8
        confirmpwd.layer.borderColor = UIColor.gray.cgColor
        
    }
    
    func rememberlogin(){
        let saveSuccessful:Bool=KeychainWrapper.standard.set(mphone!, forKey:"rusername")
        KeychainWrapper.standard.set(wname!, forKey:"rname")
        KeychainWrapper.standard.set(wuserid!, forKey:"ruserid")
        KeychainWrapper.standard.set(true, forKey:"rloginsuccess")
        print("存储账号",saveSuccessful)
    }
}
